package it.traveldream.ManagedBeans;

import it.traveldream.EJB.CityCountryBean;
import it.traveldream.EJB.DTO.StatoDTO;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;


@ManagedBean(name="statiBean")
@FacesConverter(value="statiConv")
public class StatiBean implements Converter{

	
	
	private ArrayList<StatoDTO> listaStatiFiltrati;
	
	@EJB
	private CityCountryBean cityEJB;
	
	public StatiBean(){
		setListaStatiFiltrati(new ArrayList<StatoDTO>());
	}
	
	
	
	public List<StatoDTO> complete(String q){
		
		listaStatiFiltrati.addAll(cityEJB.getAllStati());
		ArrayList<StatoDTO> help =  new ArrayList<StatoDTO>();
		Iterator<StatoDTO> it = listaStatiFiltrati.iterator();
		StatoDTO s;
		while(it.hasNext()){
			s = it.next();
			if(s.getName().toLowerCase().startsWith(q.toLowerCase()))
				help.add(s);
		}
		
		listaStatiFiltrati.clear();
		listaStatiFiltrati.addAll(help);
		
		System.out.println("Stati filtrati: " + listaStatiFiltrati.size() + " su "+ cityEJB.getAllStati().size());
		
		return listaStatiFiltrati;
		
	}
	
	
	
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {

		if(value.length() == 0) return null;
		listaStatiFiltrati.addAll(cityEJB.getAllStati());
		Iterator<StatoDTO> it = listaStatiFiltrati.iterator();
		StatoDTO s;
		while(it.hasNext()){
			s = it.next();
			if(s.getName().equalsIgnoreCase(value))
				return s;
		}
		s = new StatoDTO();
		s.setCode("");
		s.setName("");
		return s;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {

		StatoDTO s = (StatoDTO) value;
		return s.getName();
	}




	public ArrayList<StatoDTO> getListaStatiFiltrati() {
		return listaStatiFiltrati;
	}




	public void setListaStatiFiltrati(ArrayList<StatoDTO> listaStatiFiltrati) {
		this.listaStatiFiltrati = listaStatiFiltrati;
	}
	
	

}
